package com.estore.network;

import com.estore.entity.Product;
import java.io.*;
import java.net.*;
import java.util.List;
import java.util.Scanner;

public class EStoreClient {
    private static final String SERVER_HOST = "localhost";
    private static final int SERVER_PORT = 8888;
    private Scanner scanner;

    public EStoreClient() {
        this.scanner = new Scanner(System.in);
    }

    public void start() {
        System.out.println("=== 电子商城客户端 ===");

        while (true) {
            showMenu();
            int choice = getMenuChoice();

            switch (choice) {
                case 1:
                    browseProducts();
                    break;
                case 2:
                    getServerInfo();
                    break;
                case 0:
                    System.out.println("感谢使用，再见！");
                    return;
                default:
                    System.out.println("无效选择，请重新输入。");
            }

            System.out.println("\n按回车键继续...");
            scanner.nextLine();
        }
    }

    private void showMenu() {
        System.out.println("\n=== 主菜单 ===");
        System.out.println("1. 浏览所有商品");
        System.out.println("2. 获取服务器信息");
        System.out.println("0. 退出");
        System.out.print("请选择操作: ");
    }

    private int getMenuChoice() {
        try {
            return Integer.parseInt(scanner.nextLine());
        } catch (NumberFormatException e) {
            return -1;
        }
    }

    private void browseProducts() {
        System.out.println("\n正在连接服务器获取商品列表...");

        try (Socket socket = new Socket(SERVER_HOST, SERVER_PORT);
             ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
             ObjectInputStream input = new ObjectInputStream(socket.getInputStream())) {

            // 设置连接超时
            socket.setSoTimeout(10000);

            // 发送请求
            output.writeObject("GET_ALL_PRODUCTS");
            output.flush();

            // 接收响应
            Object response = input.readObject();

            if (response instanceof List) {
                @SuppressWarnings("unchecked")
                List<Product> products = (List<Product>) response;
                displayProducts(products);
            } else {
                System.out.println("服务器返回了意外的响应: " + response);
            }

        } catch (ConnectException e) {
            System.err.println("连接服务器失败，请确保服务器已启动！");
        } catch (SocketTimeoutException e) {
            System.err.println("连接超时，请检查网络连接！");
        } catch (IOException e) {
            System.err.println("网络通信错误: " + e.getMessage());
        } catch (ClassNotFoundException e) {
            System.err.println("数据解析错误: " + e.getMessage());
        }
    }

    private void getServerInfo() {
        System.out.println("\n正在获取服务器信息...");

        try (Socket socket = new Socket(SERVER_HOST, SERVER_PORT);
             ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
             ObjectInputStream input = new ObjectInputStream(socket.getInputStream())) {

            socket.setSoTimeout(5000);

            output.writeObject("GET_SERVER_INFO");
            output.flush();

            Object response = input.readObject();
            System.out.println("服务器信息: " + response);

        } catch (ConnectException e) {
            System.err.println("连接服务器失败，请确保服务器已启动！");
        } catch (IOException | ClassNotFoundException e) {
            System.err.println("获取服务器信息失败: " + e.getMessage());
        }
    }

    private void displayProducts(List<Product> products) {
        System.out.println("\n=== 商品列表 ===");
        if (products == null || products.isEmpty()) {
            System.out.println("暂无商品");
        } else {
            System.out.println("编号\t商品名称\t\t价格\t\t库存\t描述");
            System.out.println("------------------------------------------------------------");
            for (int i = 0; i < products.size(); i++) {
                Product product = products.get(i);
                System.out.printf("%d\t%-12s\t￥%-8.2f\t%-4d\t%s%n",
                        i + 1, product.getName(), product.getPrice(),
                        product.getStock(), product.getDescription());
            }
            System.out.println("------------------------------------------------------------");
            System.out.println("共找到 " + products.size() + " 个商品");
        }
    }

    public static void main(String[] args) {
        EStoreClient client = new EStoreClient();
        client.start();
    }
}